#!/usr/bin/env python
# coding: utf-8


import os,shutil
import time,datetime
import wave
import numpy as np
import warnings
import pandas as pd
import collections
import json

warnings.filterwarnings("ignore")


class Intimacy_sys():
    '''
    亲密度系统(Intimacy system)
    目前有三种亲密层次：陌生人（<20）、朋友(21-60)和家人(>60)
    每天都会重新计算亲密度
    把所有要用到的数据都保存到文件中，供以递增亲密系统使用
    亲密系统影响因子有：人脸出现次数、主人声纹出现次数、亲昵话语出现次数、行为类出现次数（抚摸抱起等）与当日总出现次数
    '''
    def __init__(self):
        #self.picture_path= picture_path
        self.now_date =  time.strftime('%Y-%m-%d',time.localtime(time.time()))
        self.face_path = 'faces.log'
        tree=lambda:collections.defaultdict(tree)
        self.Inti_dict = tree()
        self.Inti = tree()
        self.audio_path = 'audio_wav_de_txt'

    def get_speaker_times(self):
        '''
        从声纹返回结果或者信息
        以声纹库中每个主人音频的数量作分数，获取总音频数量与当日创建的音频数量
        把信息都保存到Inti_dict中
        每日递增加分：
            d——>30次（一天积累大于5分钟）+4
            c——19-30（一天积累3-5min）+3
            b——7-18（一天积累1-3min）+2
            a ——1-6（一天1min内）+1
        '''
        for name in os.listdir(self.audio_path):
            if name != 'unknown':
                people_path = os.path.join(self.audio_path,name)
                audio_now_num = 0
                for audio in os.listdir(people_path):
                    audio_file = os.path.join(people_path, audio)
                    timestamp = os.path.getmtime(audio_file)
                    date = time.strftime('%Y-%m-%d',time.localtime(timestamp)) #获取当前文件最近修改时间
                    if self.now_date == date:
                        audio_now_num = audio_now_num + 1
                        #print([audio_file, audio_file_date])
                #根据总次数划分等级，不同等级加不同分
                # if len(os.listdir(people_path)) > 180 : spe_le = 2
                # elif len(os.listdir(people_path)) > 90 : spe_le = 1.5
                # elif len(os.listdir(people_path)) > 30 : spe_le = 1
                # elif len(os.listdir(people_path)) > 0 : spe_le = 0.5
                # else : spe_le = 0
                
                if audio_now_num > 30 : spe_today_le = 2
                elif audio_now_num > 18 : spe_today_le = 1.5
                elif audio_now_num > 6 : spe_today_le = 1
                elif audio_now_num > 0 : spe_today_le = 0.5
                else : spe_today_le = 0
                self.Inti_dict[name]['speaker_all_times'] = len(os.listdir(people_path))
                #self.Inti_dict[name]['speaker_all_times_le'] = spe_le
                self.Inti_dict[name]['speaker_day_times'] = audio_now_num
                self.Inti_dict[name]['speaker_day_times_le'] = spe_today_le
        
    def face_sys(self):
        '''
        获取人脸识别信息,未完成
        以人脸识别库中每个主人人脸出现的的数量作分数
        同时计算当天人脸出现的数量
        每日递增加分：
                d——>30次（一天积累大于5分钟）+6
                c——18-30（一天积累3-5min）+4.5
                b——7-18（一天积累1-3min）+3
                a ——1-6（一天1min内）+1.5
        '''
        
        face_list = []
        with open(self.face_path, 'r' ,encoding = 'utf-8') as f:
            lines = f.readlines()
        f.close()
        for line in lines:
            face_list.append([line.split(' ')[0], line.split(' ')[1].split(',')[0], 
                             line.split(' ')[3].split('\t')[0], line.split(' ')[3].split('\t')[1],
                             line.split(' ')[4].split('\n')[0]])

        face_frame = pd.DataFrame(face_list, columns = ['date', 'time','name',  'date2' , 'timing'])
        for name in face_frame['name'].unique():
            if name != 'unknown':
                frame_name = face_frame[face_frame['name'] == name]
                # if len(frame_name) > 180 : face_le = 4
                # elif len(frame_name) > 90 : face_le = 3
                # elif len(frame_name) > 30 : face_le = 2
                # elif len(frame_name) > 0 : face_le = 1
                # else : face_le = 0
                #print(self.now_date)
                frame_date = frame_name[frame_name['date'] == self.now_date]
                #print( face_frame['date'] )
                if len(frame_date) > 30 : face_today_le = 3
                elif len(frame_date) > 18 : face_today_le =2.25
                elif len(frame_date) > 6 : face_today_le = 1.5
                elif len(frame_date) > 0 : face_today_le = 0.75
                else : face_today_le = 0

                print(len(frame_date))
                self.Inti_dict[name]['face_all_times'] = len(frame_name)
                #self.Inti_dict[name]['face_all_times_le'] = face_le
                self.Inti_dict[name]['face_day_times'] = len(frame_date)
                self.Inti_dict[name]['face_day_times_le'] = face_today_le
        
    def asr_talk(self):
        '''
        说亲昵内容次数（如：喜欢你、你好可爱等表达赞美与爱意的语句）。通过语音识别，把关键词获取下来。只要有一次就递增。这里只计算总次数
        这里也要计算当日次数。
        亲昵内容包括：‘喜欢你’,'可爱'，‘陪伴’，‘陪着’
        每日递增加分：
                d——>30次（一天积累大于5分钟）+2
                c——18-30（一天积累3-5min）+1.5
                b——7-18（一天积累1-3min）+1
                a ——1-6（一天1min内）+0.5
        '''
        self.Inti_dict['lingli']['asr_all_times'] = 20
        # self.Inti_dict[name]['face_all_times_le'] = face_le
        self.Inti_dict['lingli']['asr_day_times'] = 3
        self.Inti_dict['lingli']['asr_day_times_le'] = 0.25
        self.Inti_dict['linkunling']['asr_all_times'] = 20
        # self.Inti_dict[name]['face_all_times_le'] = face_le
        self.Inti_dict['linkunling']['asr_day_times'] = 20
        self.Inti_dict['linkunling']['face_day_times_le'] = 0.75

    def torch_action(self):
        '''
        说亲昵内容次数（如：喜欢你、你好可爱等表达赞美与爱意的语句）。通过语音识别，把关键词获取下来。只要有一次就递增。这里只计算总次数
        这里也要计算当日次数。
        亲昵内容包括：‘喜欢你’,'可爱'，‘陪伴’，‘陪着’
        递增函数加分：
                d——>30次（一天积累大于5分钟）+4
                c——18-30（一天积累3-5min）+3
                b——7-18（一天积累1-3min）+2
                a ——1-6（一天1min内）+1
        '''
        self.Inti_dict['xiefei_a5']['torch_all_times'] = 10
        # self.Inti_dict[name]['face_all_times_le'] = face_le
        self.Inti_dict['xiefei_a5']['torch_day_times'] = 3
        self.Inti_dict['xiefei_a5']['torch_day_times_le'] = 0.5
        self.Inti_dict['linkunling']['torch_all_times'] = 40
        # self.Inti_dict[name]['face_all_times_le'] = face_le
        self.Inti_dict['linkunling']['torch_day_times'] = 10
        self.Inti_dict['linkunling']['torch_day_times_le'] = 1

    def get_ori_day_score(self):
        '''
        获取上一天的亲密度分数，仅用于递增亲密系统
        '''
        f = open("inti_score.json", encoding='utf-8')
        self.ori_inti_score = json.load(f)


    def love_score(self):
        '''
        该函数是计算每位主人当日接触次数同时计算总得分（多元及递增）
        每日递增加分：
                d——>30次（一天积累大于5分钟）+4
                c——18-30（一天积累3-5min）+3
                b——7-18（一天积累1-3min）+2
                a ——1-6（一天1min内）+1
                e:0（-1）
        '''
        self.get_ori_day_score()
        self.get_speaker_times()
        self.face_sys()
        #print(json.dumps(self.Inti_dict))
        self.asr_talk()
        self.torch_action()
        
        #计算所有当日的总次数，以此判断主人当日是否接触机器人
        for name_num in range(len(self.Inti_dict)):
            name = list(self.Inti_dict.keys())[name_num]
            #print(name)

            #计算每日次数以及每日次数对应的等级（多元线性）
            if 'speaker_day_times' in self.Inti_dict[name] :
                speaker_day_times = self.Inti_dict[name]['speaker_day_times']
            else : speaker_day_times = 0
            if  'face_day_times' in self.Inti_dict[name] :
                face_day_times = self.Inti_dict[name]['face_day_times']
            else : face_day_times = 0
            if  'asr_day_times' in self.Inti_dict[name] :
                asr_day_times = self.Inti_dict[name]['asr_day_times']
            else : asr_day_times = 0
            if  'torch_day_times' in self.Inti_dict[name] :
                torch_day_times = self.Inti_dict[name]['torch_day_times']
            else : torch_day_times = 0

            day_times = speaker_day_times + face_day_times + asr_day_times + torch_day_times
            if day_times ==0 : day_times = -1

            #计算多元线性方程，比例是[人脸：声纹：亲昵话语:行为:每日] = [3:2:1:2:2]
            if 'speaker_all_times' in self.Inti_dict[name]:
                speaker_all_times = self.Inti_dict[name]['speaker_all_times']
            else :speaker_all_times = 0
            if 'face_all_times' in self.Inti_dict[name]:
                face_all_times = self.Inti_dict[name]['face_all_times']
            else :face_all_times = 0
            if 'asr_all_times' in self.Inti_dict[name]:
                asr_all_times = self.Inti_dict[name]['asr_all_times']
            else :asr_all_times = 0
            if 'torch_all_times' in self.Inti_dict[name]:
                torch_all_times = self.Inti_dict[name]['torch_all_times']
            else :torch_all_times = 0
            #y_times = 0.25*audio_day_times_score + 0.5*frame['face_all_times'][i] + 0.15*frame['asr_times'][i] + 0.1*frame['day_times'][i]
            y_times = 0.4*speaker_all_times + 0.6*face_all_times + + 0.2*asr_all_times + 0.4*torch_all_times +0.4*day_times
            y_times = y_times/2
            if y_times >100 : y_times = 100# 设置上限为100
            if y_times < 0 : y_times = 0

            #计算次数每日递增，这里递增是根据每日出现的次数划分等级的。
            if 'speaker_day_times_le' in self.Inti_dict[name]:
                speaker_day_times_le = self.Inti_dict[name]['speaker_day_times_le']
            else : speaker_day_times_le = 0
            if  'face_day_times_le' in self.Inti_dict[name]:
                face_day_times_le = self.Inti_dict[name]['face_day_times_le']
            else : face_day_times_le = 0
            if 'asr_day_times_le' in self.Inti_dict[name]:
                asr_day_times_le = self.Inti_dict[name]['asr_day_times_le']
            else : asr_day_times_le = 0
            if  'torch_day_times_le' in self.Inti_dict[name]:
                torch_day_times_le = self.Inti_dict[name]['torch_day_times_le']
            else : torch_day_times_le = 0


            #day_all_score = face_day_times + speaker_day_times
            if day_times > 30: day_times_le = 2
            elif day_times > 10:day_times_le = 1.5
            elif day_times > 5:day_times_le = 1
            elif day_times > 0:day_times_le = 0.5
            else:day_times_le = -1
            #print(ori_score)
            #y_le = ori_score  + face_all_times_le +  speaker_day_times_le  + day_times_score_le
            if name in self.ori_inti_score.keys():
                ori_score = self.ori_inti_score[name]['day_score']
            y_le = ori_score + face_day_times_le + speaker_day_times_le + asr_day_times_le +  torch_day_times_le + day_times_le
            if y_le < 0 : y_le = 0
            if y_le > 100 : y_le = 100 # 设置下限为0，上限为100


            #print(name, y_times, y_le)
            #把以上两个公式计算出来的亲密度添加到字典中
            self.Inti[name]['times_score'] = y_times
            self.Inti[name]['day_score'] = y_le
            self.Inti[name]['torch_all_times'] = torch_all_times

        #把亲密度信息保存到json文件中
        json_str = json.dumps(self.Inti_dict)
        #print(json_str)
        with open('inti_info.json', 'w') as json_file:
            json_file.write(json_str)

        json_str2 = json.dumps(self.Inti)
        #print(json_str2)
        with open('inti_score.json', 'w') as json_file2:
            json_file2.write(json_str2)



if __name__ == '__main__':
    love_sys = Intimacy_sys()
    love_sys.love_score()







